package app

import (
	"github.com/fuxiaohei/hxgo"
	"path"
	"os"
	"encoding/json"
	"github.com/Unknwon/com"
)

/*
	App Config
 */

// config vars
var (
	// global config struct
	// it has merged app.conf and [runMode].conf
	Cfg *hxgo.Config
	cfgData map[string]string
)

// init default config data, waiting for writing app.conf
func init() {
	cfgData = map[string]string{
		"AppName":"HxGo",
		"AppVersion":HxGo_AppVersion,
		"RunMode":RunMode_Dev,
		"HttpPort":"8080",
		"HttpGzip":"false",
		"Language":"zh-cn",
		"DbEnable":"false",
		"DbDriver":"",
		"DbDsn":"",
		"DbConnMax":"",
		"CacheEnable":"false",
		"CacheType":"",
		"ViewCache":"false",
		"ViewErrorPage":"error.html",
	}
}

// set config data for writing
func WriteConf(k string, v string) {
	cfgData[k] = v
}

// load config data from one file
// if file is missing, return error
func Config(file string, tp int) (*hxgo.Config, error) {
	f := path.Join(Root, file)
	if !com.IsFile(f) {
		return nil, os.ErrNotExist
	}
	return hxgo.NewConfig(f, tp), nil
}

// init default config
func initConfig() {
	// read app.conf
	f := path.Join(Root, "app.conf")
	if !com.IsFile(f) {
		// if app.conf isn't existed, write default app.conf
		writeDefaultConfig(f)
		Log.Info("[" + Name + "]", "write app.conf")
	}
	// load app.conf
	Cfg = hxgo.NewConfig(f, hxgo.CONFIG_JSON)
	Log.Info("[" + Name + "] load app.conf")
	// load runMode conf
	loadRunModeConfig(Cfg.String("RunMode"))
	// export some config data to global vars
	exportConfigData()
}

// write default config file
func writeDefaultConfig(f string) {
	// write json to default file
	jsonBytes, _ := json.MarshalIndent(cfgData, "", "  ")
	// create app.conf file
	fs, e := os.Create(f)
	if e != nil {
		panic(e)
	}
	defer fs.Close()
	fs.Write(jsonBytes)
}

// load config file for current running mode
func loadRunModeConfig(mode string) {
	f := path.Join(Root, mode + ".conf")
	if com.IsFile(f) {
		nCfg := hxgo.NewConfig(f, hxgo.CONFIG_JSON)
		// replace running-mode config file into app.conf json
		for k, v := range nCfg.Data {
			Cfg.Data[k] = v
		}
		Log.Info("[" + Name + "] load " + mode + ".conf")
	}
}

// export data to global vars
func exportConfigData() {
	RunMode = Cfg.String("RunMode")
	Name = Cfg.String("AppName")
	Version = Cfg.String("AppVersion")
}

